# syntax=docker/dockerfile:1.2
FROM rust:1.78.0-alpine as builder
WORKDIR /app
ENV RUSTFLAGS="-C target-feature=-crt-static"
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
  && apk add openssl-dev build-base \
  && rm /var/cache/apk/*

# 做一个假的main.rs参与构建，目的是建立依赖的缓存
COPY Cargo.toml .
RUN echo "fn main() {println!(\"Hello, world!\");}" > dummy.rs
RUN sed -i 's/src\/main.rs/dummy.rs/' Cargo.toml
ARG CACHE_FLAG=1
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,sharing=private,target=target \
    cargo build --release
COPY . .
# 真实的构建，注意mount只在同一层layer生效，所以在同一层构建完成后就要马上mv出去
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,sharing=private,target=target \
    cargo build --release && mv target/release/demo-cache .

FROM alpine:latest
WORKDIR /app
ENV TZ=Asia/Shanghai
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
    && apk add tzdata libgcc \
    && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
    && echo $TZ > /etc/timezone \
    && rm /var/cache/apk/*

COPY --from=builder /app/demo-cache /app/demo-cache

CMD /app/demo-cache
